import Cookie from 'js-cookie'
import ajax from './ajax'
import router from '../router'
import Utils from './utils';

const base_uri = 'http://localhost:8080';
const client = {
    client_id: 'client',
    client_secret: 'secret',
    scope: 'user',
    grant_type: 'authorization_code',
    authorize_uri: base_uri + '/oauth/authorize',
    token_uri: base_uri + '/oauth/token',
    redirect_uri: 'http://localhost',
    user_info_uri: base_uri + '/user',
    logout_uri: base_uri + '/logout',
    check_token_uri: base_uri + '/oauth/check_token'
};

const Oauth = {
    client: client,
    authorize: function () {
        let url = client.authorize_uri + '?client_id=' + client.client_id + '&response_type=code&redirect_uri='
            + client.redirect_uri + '&state=';
        let code = Utils.getUrlParms('code');
        if (code == null) {
            window.location.href = url + Math.random();
        } else {
            ajax.get(client.token_uri, {
                params: {
                    client_id: client.client_id,
                    client_secret: client.client_secret,
                    scope: client.scope,
                    grant_type: client.grant_type,
                    code: code,
                    redirect_uri: client.redirect_uri,
                    state: Utils.getUrlParms('state')
                }
            }).then(function (token) {
                history.pushState('', 'Title', '/');
                Cookie.set('access_token', token.access_token);
                router.go("/dashboard")
            }).catch(function () {
                window.location.href = url + Math.random();
            });
        }
    },
    loadUserInfo: async function () {
        ajax.get("/admin/admin");
        return await ajax.post(client.user_info_uri);
    },
    getToken: function () {
        return Cookie.get('access_token');
    },
    removeToken: function () {
        Cookie.remove('access_token');
    },
    logout: function () {
        ajax.get(client.logout_uri, {
            params: {
                access_token: Cookie.get('access_token')
            }
        }).then(function (res) {
            if (res.status == 1) {
                Oauth.removeToken();
                Oauth.authorize();
            }
        });
    }
};

export default Oauth;
